// 封装购物车

import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

export const useCartStore = defineStore(
  'cart',
  () => {
    // 1. 定义state - cartList
    const cartList = ref([])
    //2 定义action -addCart
    const addCart = (goods) => {
      // 添加购物车的操作
      // 已添加过 - count + 1 没添加过 - 直接push
      const item = cartList.value.find((item) => goods.skuId === item.skuId)

      if (item) {
        // 找到了
        item.count++
      } else {
        cartList.value.push(goods)
      }
    }
    // 删除购物车
    const delCart = (skuId) => {
      // 思路1： 找到删除项的下标值，splice
      // 思路2： 使用数组的过滤方法 - filter
      const idx = cartList.value.findIndex((item) => skuId === item.skuId)
      cartList.value.splice(idx, 1)
    }
    // 单选功能
    const singleCheck = (skuId, selected) => {
      const item = cartList.value.find((item) => item.skuId === skuId)
      item.selected = selected
    }
    // 全选功能
    const allCheck = (selected) => {
      // cartList 中的每一项都设置为全选
      cartList.value.forEach((item) => (item.selected = selected))
    }
    // 计算属性
    // 1.总的数量 - 所有项count之和
    // 2.总价 - 所有项的count * price之和
    const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
    const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
    // 已选择的数量
    const selectedCount = computed(() => cartList.value.filter((item) => item.selected).reduce((a, c) => a + c.count, 0))
    const selectedPrice = computed(() => cartList.value.filter((item) => item.selected).reduce((a, c) => a + c.count * c.price, 0))

    // 是否全选
    const isAll = computed(() => cartList.value.every((item) => item.selected))

    return {
      cartList,
      addCart,
      delCart,
      allCount,
      allPrice,
      singleCheck,
      isAll,
      allCheck,
      selectedCount,
      selectedPrice,
    }
  },
  {
    persist: true,
  },
)
